package com.sofwin.realm;

import com.sofwin.pojo.SysRole;
import com.sofwin.pojo.SysUser;
import com.sofwin.service.RoleService;
import com.sofwin.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @packageName: com.sofwin.realm
 * @user: andyliu
 * @date: 2023/5/19 16:57
 * @email 115176513@qq.com
 * @description: TODO
 */
public class MyRealm extends AuthorizingRealm {

    private UserService userService;

    private RoleService roleService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入到授权方法.........");
        String loginName = principalCollection.getPrimaryPrincipal().toString();
        SysUser loginUser = new SysUser();
        loginUser.setLoginName(loginName);
        SysUser user = userService.login(loginUser);
        SysRole role = roleService.queryById(user.getRoleId());
        Set<String> permissions = roleService.queryRolePermissions(role.getId());
        // securityManage知道当前用户有哪些角色
        // 知道当前用户有哪些资源
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(role.getRoleName());
        info.addStringPermissions(permissions);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String loginName = token.getPrincipal().toString();
        SysUser loginUser = new SysUser();
        loginUser.setLoginName(loginName);
        SysUser user = userService.login(loginUser);
        if(user==null){
            throw new UnknownAccountException();
        }
        if(user.getStatus()==1){
            throw new LockedAccountException();
        }
        return new SimpleAuthenticationInfo(loginName,user.getLoginPwd(), ByteSource.Util.bytes(loginName),this.getName());
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
}
